package com.xhui.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhui.reggie.common.BaseContext;
import com.xhui.reggie.common.CustomException;
import com.xhui.reggie.common.R;
import com.xhui.reggie.dto.OrderDTO;
import com.xhui.reggie.entity.*;
import com.xhui.reggie.mapper.OrderMapper;
import com.xhui.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * Author XHui
 * Date 2023/1/21 21:29
 * Version 1.0
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders>
        implements OrderService {

    @Resource
    private ShoppingCartService shoppingCartService;

    @Resource
    private UserService userService;

    @Resource
    private AddressBookService addressBookService;

    @Resource
    private OrderDetailService orderDetailService;


    /**
     * 用户下单
     *
     * @param orders --> addressBookId payMethod remark
     */
    @Override
    @Transactional
    public void submit(Orders orders) {

        Long userId = BaseContext.getCurrentId();
        // 根据userId查询用户对应的购物车中的所有数据
        LambdaQueryWrapper<ShoppingCart> shoppingCartWrapper = new LambdaQueryWrapper<>();
        shoppingCartWrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> cartList = shoppingCartService.list(shoppingCartWrapper);

        if (cartList == null || cartList.size() == 0) {
            throw new CustomException("购物车为空，不能下单");
        }

        // 查询用户数据
        User user = userService.getById(userId);

        // 查询收货地址信息
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if (addressBook == null) {
            throw new CustomException("用户地址信息为空，不能下单");
        }

        long orderNumber = IdWorker.getId();

        // 使用原子类整数，保证线程安全
        AtomicInteger amount = new AtomicInteger(0);
        List<OrderDetail> orderDetails = cartList.stream().map(item -> {

            OrderDetail orderDetail = new OrderDetail();

            orderDetail.setOrderId(orderNumber); // 订单id
            orderDetail.setNumber(item.getNumber()); // 菜品数量
            orderDetail.setDishFlavor(item.getDishFlavor()); //
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());


        orders.setNumber(String.valueOf(orderNumber)); // 设置订单号
        orders.setId(orderNumber);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));
        orders.setUserId(userId);
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(user.getPhone());
        orders.setAddress(
                (addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName()) +
                        (addressBook.getCityName() == null ? "" : addressBook.getCityName()) +
                        (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName()) +
                        (addressBook.getDetail() == null ? "" : addressBook.getDetail())
        );
        // 向订单表中插入一条数据(订单基本数据) --> orders
        this.save(orders);

        // 向订单详细表中插入多条数据(详细菜品数据) --> order_detail
        orderDetailService.saveBatch(orderDetails);

        // 下单成功之后，需要清空购物车数据
        shoppingCartService.remove(shoppingCartWrapper);
    }

    /**
     * 查询详细订单
     *
     * @param page     页码
     * @param pageSize 页数
     * @return 详细信息
     */
    @Override
    public Page<OrderDTO> orderDetails(int page, int pageSize) {

        // 获取当前用户id
        Long userId = BaseContext.getCurrentId();

        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> ordersQueryWrapper = new LambdaQueryWrapper<>();
        ordersQueryWrapper.eq(Orders::getUserId, userId);
        ordersQueryWrapper.orderByDesc(Orders::getOrderTime);

        // 根据用户id查询 --> orders -> orderTime、status、amount
        this.page(ordersPage, ordersQueryWrapper);
        List<Orders> records = ordersPage.getRecords();

        List<OrderDTO> orderDTOS = records.stream().map(orders -> {

            // 通过查询到的orders进行封装为 -> orderDTO
            OrderDTO orderDTO = new OrderDTO();
            BeanUtils.copyProperties(orders, orderDTO);

            // 然后根据orders的id 获取到orderDetails -> order_detail
            LambdaQueryWrapper<OrderDetail> orderDetailQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailQueryWrapper.eq(OrderDetail::getOrderId, orders.getId());
            List<OrderDetail> orderDetails = orderDetailService.list(orderDetailQueryWrapper);

            orderDTO.setOrderDetails(orderDetails);
            return orderDTO;



        }).collect(Collectors.toList());

        Page<OrderDTO> orderDTOPage = new Page<>();
        BeanUtils.copyProperties(ordersPage, orderDTOPage, "records");
        orderDTOPage.setRecords(orderDTOS);

        return orderDTOPage;
    }
}
